import 'dart:async';
import 'package:e_reception_flutter/constants/constant.dart';
import 'package:e_reception_flutter/singleton/theme_repository/theme_repository.dart';
import 'package:e_reception_flutter/ui/building_index/building_index_module_list_response_bean.dart';
import 'package:e_reception_flutter/ui/building_index/smart_home_water_list_response_bean.dart';
import 'package:e_reception_flutter/ui/smart_home/smart_home_category_response_bean.dart';
import 'package:e_reception_flutter/ui/smart_home/smart_home_view_model.dart';
import 'package:e_reception_flutter/utils/router_utils.dart';
import 'package:e_reception_flutter/utils/screen_utils.dart';
import 'package:e_reception_flutter/utils/vg_global_func.dart';
import 'package:e_reception_flutter/vg_widgets/light_annotated_region_style.dart';
import 'package:e_reception_flutter/vg_widgets/vg_image_widget/vg_cache_net_work_image.dart';
import 'package:e_reception_flutter/vg_widgets/vg_photo_preview/vg_photo_preview.dart';
import 'package:e_reception_flutter/vg_widgets/vg_place_holder_status_widget/vg_place_holder_status_widget.dart';
import 'package:e_reception_flutter/vg_widgets/vg_pull_to_refresh_widget/vg_pull_to_refresh_widget.dart';
import 'package:e_reception_flutter/vg_widgets/vg_top_bar_widget/vg_top_bar_widget.dart';
import 'package:flutter/cupertino.dart';
import 'package:flutter/material.dart';
import 'package:photo_preview/photo_preview_export.dart';
import 'package:vg_base/vg_arch_lib.dart';
import 'package:vg_base/vg_string_util_lib.dart';

/// 水印列表页面
class SmartHomeWaterListPage extends StatefulWidget {
  ///路由名称
  static const String ROUTER = "SmartHomeWaterListPage";
  ///门店id
  final ComSmarthomeBean infoBean;
  const SmartHomeWaterListPage(
      {Key key, this.infoBean}) : super(key:key);

  @override
  _SmartHomeWaterListPageState createState() => _SmartHomeWaterListPageState();

  static Future<dynamic> navigatorPush(BuildContext context, ComSmarthomeBean infoBean,){
    return RouterUtils.routeForFutureResult(
        context,
        SmartHomeWaterListPage(
          infoBean: infoBean,
        ),
        routeName: SmartHomeWaterListPage.ROUTER
    );
  }

}

class _SmartHomeWaterListPageState
    extends BaseState<SmartHomeWaterListPage>{
  SmartHomeViewModel _viewModel;
  String _selectWaterId;
  String _originWaterId;
  //用于标志是否是第一次将选中的模板放到第一位
  bool _firstRange = false;
  List<WatermarkListBean> _rangeList;
  //水印开关 00开 01关
  String _waterflg;
  //00每日更换 01固定一种
  String _dayflg;
  ComSmarthomeBean _infoBean;
  @override
  void initState() {
    super.initState();
    _infoBean = widget?.infoBean;
    _waterflg = _infoBean?.watermark;
    _dayflg = _infoBean?.dayflg;
    _rangeList = new List();
    _viewModel = SmartHomeViewModel(this);
    _viewModel?.getWaterListData(context, _infoBean?.shid??"");
  }

  @override
  void dispose() {
    super.dispose();
  }

  @override
  Widget build(BuildContext context) {
    return LightAnnotatedRegion(
        child: Scaffold(
          resizeToAvoidBottomInset: false,
          resizeToAvoidBottomPadding: false,
          backgroundColor: Colors.white,
          body: _toMainColumnWidget(),
        )
    );
  }

  Widget _toMainColumnWidget() {
    return  Column(
      children: [
        _toTopBarWidget(),
        _toOpenWidget(),
        _toSelectWaterChangeFlgWidget(),
        Expanded(child: _toPlaceHolderWidget()),
      ],
    );
  }

  ///页面标题
  Widget _toTopBarWidget(){
    return VgTopBarWidget(
      isShowBack: true,
      title: "文件水印",
      titleColor: ThemeRepository.getInstance().getCardBgColor_21263C(),
      backgroundColor: Color(0XFFF6F7F9),
      // rightWidget: _toConfirmWidget(),
    );
  }

  bool _ifCanSave(){
    return (_selectWaterId != _originWaterId);
  }
  ///完成
  Widget _toConfirmWidget(){
    return GestureDetector(
      behavior: HitTestBehavior.opaque,
      onTap: (){
        if(!_ifCanSave()){
          return;
        }
        _viewModel.changeWater(context, _infoBean?.shid, _selectWaterId);
      },
      child: ClipRRect(
        borderRadius: BorderRadius.circular(12),
        child: Container(
          height: 24,
          width: 48,
          alignment: Alignment.center,
          decoration: BoxDecoration(
              color: _ifCanSave()?ThemeRepository.getInstance().getPrimaryColor_1890FF():Color(0XFFCFD4DB),
              borderRadius: BorderRadius.circular(12)
          ),
          child: Text(
            "保存",
            style: TextStyle(
                color: Colors.white,
                fontSize: 12,
                fontWeight: FontWeight.w500
            ),
          ),
        ),
      ),

    );
  }


  ///列表页
  Widget _toPlaceHolderWidget(){
    return ValueListenableBuilder(
      valueListenable: _viewModel?.statusTypeValueNotifier,
      builder:(BuildContext context, PlaceHolderStatusType value, Widget child) {
        return VgPlaceHolderStatusWidget(
          emptyOnClick: () => _viewModel?.getWaterListData(context, _infoBean?.shid??""),
          errorOnClick: () => _viewModel?.getWaterListData(context, _infoBean?.shid??""),
          loadingStatus: value == PlaceHolderStatusType.loading,
          child: _toGridPage(),
        );
      },
    );

  }

  Widget _toOpenWidget(){
    return Container(
      height: 50,
      color: Colors.white,
      child: Row(
        children: [
          SizedBox(width: 15,),
          Text(
            "启用水印",
            style: TextStyle(
                fontSize: 14,
                color: ThemeRepository.getInstance().getCardBgColor_21263C()
            ),
          ),
          Spacer(),
          GestureDetector(
            behavior: HitTestBehavior.opaque,
            onTap: (){
              setState(() {
                ("00" == _waterflg)?_waterflg = "01":_waterflg = "00";
              });
              _viewModel.changeWaterStatus(context, _infoBean?.shid, _waterflg);
            },
            child: Container(
              padding: EdgeInsets.symmetric(horizontal: 15),
              child: Image.asset(
                ("00" == _waterflg)
                    ? "images/icon_open.png"
                    :"images/icon_close_setting_floor.png",
                width: 36,
              ),
            ),
          ),
          SizedBox(width: 15,),
        ],
      ),
    );
  }

  ///水印样式选择
  Widget _toSelectWaterChangeFlgWidget(){
    return Visibility(
      visible: "00" == _waterflg,
      child: Container(
        height: 50,
        color: Colors.white,
        child: Row(
          children: [
            SizedBox(width: 15,),
            Text(
              "水印样式",
              style: TextStyle(
                  fontSize: 14,
                  color: ThemeRepository.getInstance().getCardBgColor_21263C()
              ),
            ),
            Spacer(),
            GestureDetector(
              behavior: HitTestBehavior.opaque,
              onTap: (){
                if("00" == _dayflg){
                  return;
                }
                setState(() {
                  _dayflg = "00";
                });
                _viewModel.changeWaterDayFlg(context, _infoBean?.shid, _dayflg);
              },
              child: Container(
                height: 50,
                child: Row(
                  mainAxisSize: MainAxisSize.min,
                  children: [
                    AnimatedSwitcher(
                      duration: DEFAULT_ANIM_DURATION,
                      child: Image.asset(
                        ("00" == _dayflg)
                            ?"images/icon_terminal_select.png"
                            :"images/icon_terminal_unselect.png",
                        width: 20,
                        height: 20,
                      ),
                    ),
                    SizedBox(
                      width: 4,
                    ),
                    Text(
                      "每日更换",
                      maxLines: 1,
                      overflow: TextOverflow.ellipsis,
                      style: TextStyle(
                          color: ("00" == _dayflg)?Color(0XFF21263C):Color(0XFF8B93A5),
                          fontSize: 14,
                          height: 1.2),
                    ),
                  ],
                ),
              ),
            ),
            SizedBox(width: 20,),
            GestureDetector(
              behavior: HitTestBehavior.opaque,
              onTap: (){
                if("01" == _dayflg){
                  return;
                }
                setState(() {
                  _dayflg = "01";
                });
                _viewModel.changeWaterDayFlg(context, _infoBean?.shid, _dayflg);
              },
              child: Container(
                height: 50,
                child: Row(
                  mainAxisSize: MainAxisSize.min,
                  children: [
                    AnimatedSwitcher(
                      duration: DEFAULT_ANIM_DURATION,
                      child: Image.asset(
                        ("01" == _dayflg)
                            ?"images/icon_terminal_select.png"
                            :"images/icon_terminal_unselect.png",
                        width: 20,
                        height: 20,
                      ),
                    ),
                    SizedBox(
                      width: 4,
                    ),
                    Text(
                      "固定一种",
                      maxLines: 1,
                      overflow: TextOverflow.ellipsis,
                      style: TextStyle(
                          color: ("01" == _dayflg)?Color(0XFF21263C):Color(0XFF8B93A5),
                          fontSize: 14,
                          height: 1.2),
                    ),
                  ],
                ),
              ),
            ),
            SizedBox(width: 15,),
          ],
        ),
      ),
    );
  }


  Widget _toGridPage(){
    return ValueListenableBuilder(
      valueListenable: _viewModel?.smartHomeWaterListValueNotifier,
      builder:(BuildContext context, SmartHomeWaterListDataBean dataBean, Widget child) {
        if(_rangeList.isEmpty){
          if(StringUtils.isEmpty(_selectWaterId)){
            _selectWaterId = dataBean?.wmid;
            _originWaterId = _selectWaterId;
          }
          if(dataBean != null && dataBean.watermarkList != null && dataBean.watermarkList.isNotEmpty){
            _rangeList.clear();
            List<WatermarkListBean> tempList = new List();
            tempList.addAll(dataBean.watermarkList);
            int selectIndex = 0;
            for(int i = 0; i < tempList.length; i++){
              if(_selectWaterId == tempList[i].wmid){
                selectIndex = i;
                break;
              }
            }
            _rangeList.add(tempList.removeAt(selectIndex));
            _rangeList.addAll(tempList);
            if(StringUtils.isEmpty(_selectWaterId)){
              _selectWaterId = _rangeList[0].wmid;
              _originWaterId = _selectWaterId;
            }
          }
        }
        return GridView.builder(
          padding: EdgeInsets.only(
              left: 5,
              right: 5,
              bottom: getNavHeightDistance(context)
          ),
          itemCount: _rangeList?.length ?? 0,
          physics: BouncingScrollPhysics(),
          shrinkWrap: true,
          gridDelegate: SliverGridDelegateWithFixedCrossAxisCount(
            crossAxisCount: 2,
            mainAxisSpacing: 5,
            crossAxisSpacing: 5,
            childAspectRatio: 1.0,
          ),
          itemBuilder: (BuildContext context, int index) {
            return _toGridItemWidget(context, _rangeList?.elementAt(index), index);
          },
        );
      },
    );
  }


  Widget _toGridItemWidget(BuildContext context, WatermarkListBean itemBean, int index) {
    String picUrl = "";
    if(StringUtils.isNotEmpty(itemBean?.bgUrl)){
      picUrl = itemBean?.bgUrl;
    }
    return GestureDetector(
      behavior: HitTestBehavior.opaque,
      onTap: (){
        if("00" == _dayflg){
          return;
        }
        // BuildingIndexModelDetailPage.navigatorPush(context);
        if(_selectWaterId == itemBean.wmid){
          return;
        }
        _firstRange = true;
        setState(() {
          _selectWaterId = itemBean.wmid;
        });
        _viewModel.changeWater(context, _infoBean?.shid, _selectWaterId);
      },
      child: ClipRRect(
        borderRadius: BorderRadius.circular(4),
        child: Stack(
          fit: StackFit.expand,
          children: [
            Container(
              decoration: BoxDecoration(
                  color: Colors.white
              ),
              child: VgCacheNetWorkImage(picUrl,
                fit: BoxFit.fill,
                imageQualityType: ImageQualityType.middleDown,),
            ),
            _toWaterWidget(itemBean),
            Visibility(
              visible: "01" == _dayflg,
              child: Align(
                alignment: Alignment.bottomLeft,
                child: Container(
                  height: 24,
                  alignment: Alignment.center,
                  color: (itemBean.wmid == _selectWaterId)?ThemeRepository.getInstance().getPrimaryColor_1890FF():Colors.white.withOpacity(0.6),
                  child: Image.asset(
                    "images/icon_select_model.png",
                    width: 13,
                  ),
                ),
              ),
            ),
          ],
        ),
      ),
    );
  }

  Widget _toWaterWidget(WatermarkListBean itemBean){
    double maxWidth = (ScreenUtils.screenW(context) - 15)/2 - 16;
    return Align(
      alignment: Alignment.topLeft,
      child: Row(
        children: [
          Container(
            height: 22,
            margin: EdgeInsets.all(8),
            padding: EdgeInsets.only(left: 6.4, right: 12),
            alignment: Alignment.centerLeft,
            decoration: BoxDecoration(
              color: Color(int.parse("0X${itemBean?.solidColor??"1A000000"}")),
              borderRadius: BorderRadius.circular(12),
              border: Border.all(
                  color: Color(int.parse("0X${itemBean?.borderColor??"FFFFFFFF"}")),
                  width: 0.5),
            ),
            child: Row(
              mainAxisSize: MainAxisSize.min,
              children: [
                Container(
                  width: 9,
                  alignment: Alignment.center,
                  child: Text(
                      "·",
                    style: TextStyle(
                      fontSize: 13.87,
                      color: Color(int.parse("0X${itemBean?.textColor??"FFFFFFFF"}")),
                        fontFamily: "WaterMark",
                    ),
                  ),
                ),
                SizedBox(width: 0.6,),
                Row(
                  mainAxisSize: MainAxisSize.min,
                  children: [
                    Container(
                      padding: EdgeInsets.only(top: 1.5),
                      alignment: Alignment.centerLeft,
                      child: ConstrainedBox(
                        constraints: BoxConstraints(
                          maxWidth: maxWidth - 29,
                        ),
                        child: Text(
                          StringUtils.isEmpty(_infoBean?.getTitle()??"")?"门店或品牌名":"${_infoBean?.getTitle()}",
                          style: TextStyle(
                              fontSize: 12.87,
                              color: Color(int.parse("0X${itemBean?.textColor??"FFFFFFFF"}")),
                            fontFamily: "WaterMark",
                          ),
                          maxLines: 1,
                          softWrap: true,
                          overflow: TextOverflow.ellipsis,
                        ),
                      ),
                    ),
                  ],
                ),
              ],
            ),
          ),
        ],
      ),
    );
  }
}
